package com.ton.config.data;


import com.ton.system.entity.AdminPermission;

import java.util.ArrayList;
import java.util.List;

public class PermissionTreeVo {
    private Integer id;
    private String name;
    private List<PermissionTreeVo> children;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<PermissionTreeVo> getChildren() {
        return children;
    }

    public void setChildren(List<PermissionTreeVo> children) {
        this.children = children;
    }

    public static List<PermissionTreeVo> createVo(List<AdminPermission> list) {
        List<PermissionTreeVo> voList = new ArrayList<>();
        for (AdminPermission perm : list) {
            if (perm.getParentId() == null) {
                PermissionTreeVo v = new PermissionTreeVo();
                v.setId(perm.getId());
                v.setName(perm.getPermName());
                packChildren(v, list);
                voList.add(v);
            }
        }
        return voList;
    }

    private static void packChildren(PermissionTreeVo vo, List<AdminPermission> list) {
        for (AdminPermission perm : list) {
            if (perm.getParentId() != null && perm.getParentId().equals(vo.getId())) {
                if (perm.getParentId().equals(perm.getId())) {
                    continue;
                }
                if (vo.getChildren() == null) {
                    vo.setChildren(new ArrayList<>());
                }
                PermissionTreeVo v = new PermissionTreeVo();
                v.setId(perm.getId());
                v.setName(perm.getPermName());
                vo.getChildren().add(v);
                packChildren(v, list);
            }
        }
    }
}
